package com.stu.book.java8sz2.char16;

import org.junit.jupiter.api.Test;

import java.util.concurrent.*;

/**
 * @Classname D
 * @Version 1.0.0
 * @Date 2022/2/19 11:35
 * @Created by yd
 */
public class D {
    @Test
    public void testFuture() {
        ExecutorService executor = Executors.newCachedThreadPool();
        Future<Double> future = executor.submit(new Callable<Double>() {
            @Override
            public Double call() throws Exception {
                return doSomeLongComputation();
            }
        });
        doSomethingElse();

        try {
            //接受一个超时的参数，通过它，你可以定义你的线程等待 Future 结果的最长时间 ,而不是用无止境等待下去
            Double result = future.get(1, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            //计算抛出一个异常
            e.printStackTrace();
        } catch (ExecutionException e) {
            //当前线程在等待过程中被中断
            e.printStackTrace();
        } catch (TimeoutException e) {
            //在future 对象完成之前超时
            e.printStackTrace();
        }
        executor.shutdown();
    }

    private void doSomethingElse() {
        System.out.println("D.doSomethingElse");
    }

    private Double doSomeLongComputation() {
        return ThreadLocalRandom.current().nextDouble();
    }
}
